#!/usr/bin/python
# coding:utf-8
# servo_control.py

import RPi.GPIO as GPIO
import time

def servo_map(before_value, before_range_min, before_range_max, after_range_min, after_range_max):
    """
    功能: 将某个范围的值映射为另一个范围的值
    参数： 原范围某值，原范围最小值，原范围最大值，变换后范围最小值，变换后范围最大值
    返回： 变换后范围对应某值
    """
    percent = (before_value - before_range_min) / (before_range_max - before_range_min)
    after_value = after_range_min + percent * (after_range_max - after_range_min)
    return after_value

# GPIO设置
GPIO.setmode(GPIO.BOARD)
servo_SIG = 7
servo_freq = 50

# 占空比范围
servo_width_min = 2.5
servo_width_max = 12.5

# 设置GPIO
GPIO.setup(servo_SIG, GPIO.OUT)
servo = GPIO.PWM(servo_SIG, servo_freq)  # 信号引脚=servo_SIG 频率=servo_freq in HZ
servo.start(0)

initial_position = 135
dc_initial = servo_map(initial_position, 0, 180, servo_width_min, servo_width_max)
servo.ChangeDutyCycle(dc_initial)
print('舵机已转到135°位置')
time.sleep(2)  # 等待舵机转动到位

# 等待用户输入
try:
    while True:
        position = input("请输入0°-180°的角度值：\n")
        if position.isdigit():
            dc = int(position)
            if 0 <= dc <= 180:
                dc_trans = servo_map(dc, 0, 180, servo_width_min, servo_width_max)
                servo.ChangeDutyCycle(dc_trans)
                print(f"舵机已转动到{dc}°位置")
            else:
                print("错误输入: 超出范围")
        else:
            print("错误输入: 不是整数")
except KeyboardInterrupt:
    pass

servo.stop()  # 停止PWM
GPIO.cleanup()  # 清理GPIO设置
